package com.example.tests;

import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;

import com.example.fw.AccountHelper;
import com.example.fw.JamesHelper;
import com.example.fw.SortedListOf;
import com.example.fw.User;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;


public class SignupTest extends TestBase {
	User user = new User()
		.setLogin("testuser15")
		.setPassword("0000")
		.setEmail("testuser15@localhost.localdomain");
	
	private JamesHelper james;
	private AccountHelper accHelper;
	
	@BeforeClass
	public void createMailUser() {
		james = app.getJamesHelper();
		accHelper = app.getAccountHelper();
		if (! james.doesUserExist(user.login)) {
			james.createUser(user.login, user.password);
		}
	}
	
	@AfterClass
	public void deleteMailUser() {
		if (! james.doesUserExist(user.login)) {
			james.deleteUser(user.login);
		}
	}
	@Test
	public void delExistingUser() {
		accHelper.loginAsAdmin();
		// get old User list from UI
		SortedListOf<String> oldList = accHelper.getMantisUsers();
		// delete User
		accHelper.deleteMantisUser(user);
		// get new User list from UI
		SortedListOf<String> newList = accHelper.getMantisUsers();
		assertThat(oldList.without(user.login), equalTo(newList));
	}
	
	@Test
	public void newUserShouldSignup() {
		accHelper.signup(user);
		accHelper.login(user);
		assertThat(accHelper.loggedUser(), equalTo(user.login));
	}	
	
	@Test
	public void existingUserShouldNotSignup() {
		try {
			accHelper.signup(user);
		} catch (Exception e){
			assertThat(e.getMessage(), containsString("That username is already being used"));
		 return;
		}
		fail("Exception expected");
	}
}
